package controller

import (
	"gin-service/lib/GinSrv/GinResp"
	"gin-service/lib/GinSrv/GinRouter"
	"gin-service/lib/GormSrv"
	"gin-service/lib/GormSrv/model"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

func UserController(router GinRouter.Router) {
	router.InitRouter()
	response := new(GinResp.RespImpl)

	router.Get("/sleep", func(ctx *gin.Context) {
		timeString := ctx.Query("second")
		duration, _ := strconv.ParseInt(timeString, 10, 64)
		time.Sleep(time.Duration(duration) * time.Second)
		response.DataResp(ctx, "")
	})

	router.Get("/select", func(ctx *gin.Context) {
		userId := ctx.Query("userId")

		if userId != "" {
			var userData model.User
			GormSrv.GDB().First(&userData, userId)

			response.DataResp(ctx, userData)
		} else {
			var userList []model.User
			GormSrv.GDB().Find(&userList, userId)

			response.DataResp(ctx, userList)
		}
	})

	router.Get("/select/:userId", func(ctx *gin.Context) {
		context := ctx.Copy()
		ch := make(chan interface{})

		go func() {
			userId := context.Param("userId")
			var user model.User
			GormSrv.GDB().Find(&user, userId)

			ch<- user
		}()

		result := <-ch
		close(ch)

		response.DataResp(ctx, result)
	})

	router.Post("/insert", func(ctx *gin.Context) {
		var userForm model.User
		err := ctx.BindJSON(&userForm)
		if err != nil {
			panic(err.Error())
		}

		if userForm.UserCode == "" {
			panic("user_code missing")
		}

		if userForm.Username == "" {
			panic("username missing")
		}

		result := GormSrv.GDB().Create(&userForm)
		GormSrv.ThrowDBError(result)

		response.DataResp(ctx, result)
	})

	router.Put("/update", func(ctx *gin.Context) {
		userId := ctx.Query("userId")

		updateUser := model.User{}
		GinRouter.ThrowError(ctx.BindJSON(&updateUser))

		userData := &model.User{}
		db := GormSrv.GDB().Model(&userData).Where("user_id = ?", userId)

		if updateUser.UserCode != "" {
			db.Update("user_code", updateUser.UserCode)
		}
		if updateUser.Username != "" {
			db.Update("username", updateUser.Username)
		}

		response.DataResp(ctx, db.RowsAffected)
	})

	router.Put("/update/:userId", func(ctx *gin.Context) {
		userId := ctx.Param("userId")

		updateUser := model.User{}
		GinRouter.ThrowError(ctx.BindJSON(&updateUser))

		findUser := model.User{}
		GormSrv.GDB().First(&findUser, userId)
		GormSrv.GDB().Model(&findUser).Updates(&updateUser)

		response.DataResp(ctx, findUser)
	})

	router.Delete("/delete", func(ctx *gin.Context) {
		userId := ctx.Query("userId")
		if userId == "" {
			panic("userId missing")
		}

		result := GormSrv.GDB().Unscoped().Delete(&model.User{}, userId)
		GormSrv.ThrowDBError(result)

		response.DataResp(ctx, result)
	})

	router.Delete("/deleteAll", func(ctx *gin.Context) {
		result := GormSrv.GDB().Unscoped().Where("name is null").Delete(&model.User{})
		GormSrv.ThrowDBError(result)

		response.DataResp(ctx, result)
	})
}
